<?php
/**
 * 2017年3月16日
 */
class MY_Controller extends CI_Controller {

    function __construct(){
        parent::__construct();
        /*开启Session*/
        @session_start();
            // date_default_timezone_set('PRC');
            // 图片基础参数设置
            // 字符编码
        $this->load->helper('url');
        header ('Content-Type: text/html; charset=UTF-8');

        ini_set('memory_limit','256M');

        define('IS_GET', $_SERVER['REQUEST_METHOD'] == 'GET' ? true : false);
        define('IS_POST', $_SERVER['REQUEST_METHOD'] == 'POST' ? true : false);
        defined('LINES') OR define('LINES', '50');
        defined('TEN') OR define('TEN', '10');

        define('HW_JS',base_url().'static/js/');
        define('HW_CSS',base_url().'static/css/');
        define('HW_IMG',base_url().'static/img/');
        define('HW_UE',base_url().'static/ueditor/');
        define('HW_AdminLTE',base_url().'static/admin-lte/');

        define("APPID","wx7a3bdc9613c3f38a");
        define("APPSECRET","f234f44db085583b91617d6038cbd55c");
        define("MERCHANTID","185521432");
    }

    function trans_rollback($msg = '操作失败')
    {
        $this->db->trans_rollback();
        return array('code'=>0,'msg'=>$msg);
    }

    function trans_commit($msg = '操作成功')
    {
        $this->db->trans_commit();
        return array('code'=>1,'msg'=>$msg);
    }

        /**
         * 获取编码
         * @param  [type] $str [description]
         * @return [type]      [description]
         */
        function get_code($str)
        {
            return $str.date('ymdhis', time()).rand(0, 9).rand(0, 9);
        }

        /**
         * 检验签名
         */
        function checkSignature($param){
            if(!isset($param['Uid'])||!isset($param['signature'])){
                return false;
            }else{
                if(strcmp($param['signature'], md5($param['Uid'].date('Ymd')))==0){
                    return true;
                }else{
                    return false;
                }
            }
        }
        /**
         * 自定义操作成功页面 默认跳转操作前一个页面
         * @return [type] [description]
         */
        function success($info='',$jumpUrl='',$waitsecond=1)
        {
            if($jumpUrl==''){
                $jumpUrl = $_SERVER["HTTP_REFERER"];
            }
            $data = array(
                'info'=>$info,
                'jumpUrl'=>$jumpUrl,
                'waitsecond'=>$waitsecond,
                'status'=>1,         //表示成功操作
                'firstloc'=>'操作结果',
                'secondloc'=>'操作成功',
            );
            $this->load->view('Public/message',$data);
        }
        /*
         * 自定义操作失败页面
         * @param  string  $info       [提示信息]
         * @param  [type]  $jumpUrl    [跳转地址]
         * @param  integer $waitsecond [等待时间]
         * @return [type]              [description]
         */
        function error($info='',$jumpUrl='',$waitsecond=2){
            if($jumpUrl==''){
                $jumpUrl = $_SERVER["HTTP_REFERER"];
            }
            $data = array(
                'info'=>$info,
                'jumpUrl'=>$jumpUrl,
                'waitsecond'=>$waitsecond,
                'status'=>0,        //表示失败操作
                'firstloc'=>'操作结果',
                'secondloc'=>'操作失败',
            );
            $this->load->view('Public/message',$data);
        }

        /**
         * [无权限页面跳转]
         * @AuthorHTL
         * @DateTime  2017-08-15T11:49:53+0800
         * @param     [type] $msg [权限跳转提示]
         */
        function autherror($msg = '您无权限进行该操作')
        {
            $data['msg'] = $msg;
            $this->load->view('Public/authority', $data);
        }

        /**
         * 处理操作结果
         * @param  [type] $result [description]
         * @return [type]         [description]
         */
        function handleResult($result,$url = ''){
            if($result['code']==1){
                $this->success($result['msg'],$url);
            }else{
                $this->error($result['msg'],$url);
            }
        }

        /**
         * 正则匹配要访问的访问需要控制的权限
         * @return [type] [description]
         */
        function matchMethod($func)
        {
            // 权限控制 获取要访问的方法名 并对该方法进行正则匹配
            if (preg_match('/List|list/', $func))
            {
                $method = 'select';    
            }
            else if (preg_match('/add|Add|Insert|insert/', $func))
            {
                $method = 'add';
            }
            else if (preg_match('/edit|Edit|update|change|Update|Change/', $func))
            {
                $method = 'edit';
            }
            else if (preg_match('/del|Del|delete|Delete|cancel|Cancel/', $func))
            {
                $method = 'del';
            }
            else
            {
                $method = '';
            }

            return $method;
        }

        /*
        权限验证
        $action[模块名] $method【具体请求的方法,只有3个值 add，edit，del，select，reviewed，all】 $usergroup【用户权限组，取表的usergroup字段】
        例如：用户编辑权限判断时如下调用：
        $this->authcheck('User','edit','23');
        2017.3.27 小黑鼠
        */
        function authcheck($action, $method, $usergroup=0){
            // return true;

            $this->load->model('AuthManager/Auth_model','auth');
            //若无权限列表则根据登陆用户session去取权限组的权限
            if(!isset($_SESSION['authgroup'])){
                $_SESSION['authgroup'] = $this->auth->getsessionauth($_SESSION['admin_info']['usergroup']);
            }
            //若无需检测的权限列表则加载该列表
            // unset($_SESSION['authlist']);
            if(!isset($_SESSION['authlist'])){
                $res = $this->auth->getsessionauthname($_SESSION['admin_info']['shop_token']);
                foreach ($res as $key => $value) {
                    $authlist[]=$value['authname'];
                }  
                $_SESSION['authlist']= $authlist;
            }


            if(!in_array($action, $_SESSION['authlist'])){
                return true;
            }
            //若请求的模块在用户所在权限组里，进行进一步判断
            if(in_array($action, array_keys($_SESSION['authgroup']))){
                if(in_array($method, $_SESSION['authgroup'][$action])){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
            
        }

        /**
        * 获取分页数据
        * @param  [type] $info   [数据列表]
        * @param  [type] $page   [页数]
        * @param  [type] $url    [方法地址]
        * @param  [type] $get    [$_GET数据]
        * @return [type]         [description]
        */
        function getPage($info, $pages, $url, $get=array()){
            $count_page = isset($info['count']) && $info['count'] ? ceil($info['count']/LINES) : 1;
            $data['pageSize'] = LINES;
            $data['pageNum'] = $pages?$pages:1;
            $data['pages'] = $pages?$pages:1;

            if ($count_page == 1) {
                $data['navigatepageNums'] = array(1);
            } elseif($count_page <= 5) {
                for ($i = 1; $i <= $count_page; $i++) {
                    $data['navigatepageNums'][] = $i;
                }
            } elseif ($pages+3 > $count_page) {
                for ($i = $count_page-4; $i <= $count_page; $i++){
                    $data['navigatepageNums'][] = $i;
                }
            } else {
                if ($pages < 3) {
                    for ($i = 1; $i <= 5; $i++) {
                        $data['navigatepageNums'][] = $i;
                    }
                }else{
                    for ($i = $pages-2; $i <= $pages+2; $i++){
                        $data['navigatepageNums'][] = $i;
                    }
                }
            }

            $data['hasPreviousPage'] = $pages > 1 ? true : false;
            $data['hasNextPage'] = $pages < $count_page ? true : false;
            $data['prePage'] = $pages > 1 ? $pages - 1 : 0;
            $data['nextPage'] = $pages < $count_page ? $pages + 1 : 0;;
            $data['lastPage'] = $count_page ? $count_page : 1;
            $data['total'] = isset($info['count']) ? $info['count'] : 0;
            $data['url'] = base_url().$url;
            $data['get'] = $_SERVER['QUERY_STRING'];
            $data['list'] = isset($info['list']) ? $info['list'] : '';

            if (!empty($get)) {
                foreach ($get as $key => $value) {
                    $data[$key] = $value;
                }
            }

            return $data;
        }

        /**
         * [加密函数]
         * @Author   zt
         * @DateTime 2018-09-19
         * @param    [type]     $txt [加密内容]
         * @param    string     $key [description]
         * @return   [type]          [description]
         */
        function lock($txt,$key='ihw888888')
        {
            if (empty($txt)){
                return $txt;
            }
            $txt = $txt.$key;
            $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
            $nh = 10;
            $ch = $chars[$nh];
            $mdKey = md5($key.$ch);
            $mdKey = substr($mdKey,$nh%8, $nh%8+7);
            $txt = base64_encode($txt);
            $tmp = '';
            $i=0;$j=0;$k = 0;
            for ($i=0; $i<strlen($txt); $i++) {
                $k = $k == strlen($mdKey) ? 0 : $k;
                $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
                $tmp .= $chars[$j];
            }
            return urlencode(base64_encode($ch.$tmp));
        }

        /**
         * [解密函数]
         * @Author   zt
         * @DateTime 2018-09-19
         * @param    [type]     $txt [解密内容]
         * @param    string     $key [description]
         * @return   [type]          [description]
         */
        function unlock($txt,$key='ihw888888')
        {
            if (empty($txt)){
                return $txt;
            }

            $txt = base64_decode(urldecode($txt));
            $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
            $ch = $txt[0];
            $nh = strpos($chars,$ch);
            $mdKey = md5($key.$ch);
            $mdKey = substr($mdKey,$nh%8, $nh%8+7);
            $txt = substr($txt,1);
            $tmp = '';
            $i=0;$j=0; $k = 0;
            for ($i=0; $i<strlen($txt); $i++) {
                $k = $k == strlen($mdKey) ? 0 : $k;
                $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
                while ($j<0) $j+=64;
                $tmp .= $chars[$j];
            }
            return trim(base64_decode($tmp),$key);
        }
    }

    /**
     * 管理员
     */
    class Admin_Controller extends MY_Controller
    {
        function __construct()
        {
            parent::__construct();

            if (!isset($_SESSION['admin_info'])){

                if (Common::isAjax())
                {
                    echo json_encode(array('code'=>0,'msg'=>'您长时间未操作系统，请重新登录'));
                    exit();
                }
                else
                {
                    //跳转回商家管理员登入界面
                    echo "<script>window.alert('您的登录已失效， 请重新登录'); window.top.location.href = '".base_url()."Admin/Login/login';"."</script>";
                    exit();

                }
            }
        }
    }

    /**
     * 酒店后台
     */
    class HotelAdmin_Controller extends MY_Controller
    {
        function __construct()
        {
            parent::__construct();

            if (!isset($_SESSION['hotelAdmin_info'])){

                if (Common::isAjax())
                {
                    echo json_encode(array('code'=>0,'msg'=>'您长时间未操作系统，请重新登录'));
                    exit();
                }
                else
                {
                    //跳转回商家管理员登入界面
                    echo "<script>window.alert('您的登录已失效， 请重新登录'); window.top.location.href = '".base_url()."HotelAdmin/Login/login';"."</script>";
                    exit();

                }
            }
        }
    }

    /**
     * 微信父类
     */
    class Weixin_Controller extends MY_Controller
    {
        protected $userinfo;

        function __construct()
        {
            parent::__construct();


            // $userinfo = $this->db->select('*')->where(array('id' =>12))->get('member')->row_array();
            // setcookie('userinfo', serialize($userinfo), time()+86400, '/');
           

            if (!isset($_COOKIE['userinfo'])) {
                echo json_encode(array('code' => 403, 'msg' => '您的登录状态已失效'));exit;
            } else {
                $this->userinfo = unserialize($_COOKIE['userinfo']);
            }
        }
    }

    /**
     * api接口父类
     */
    class Api_Controller extends MY_Controller
    {
        function __construct()
        {
            parent::__construct();
        }

        /**
         * [检测签名是否正确]
         * @Author   zt
         * @DateTime 2018-09-20
         * @param    [type]     $sign [签名]
         * @param    [type]     $post [请求数据json]
         * @return   [type]           [description]
         */
        function checkSign($sign, $post)
        {
            if (empty($post)){
                $echo = array(
                    'code' => '00000',
                    'msg' => '参数丢失',
                );

                echo json_encode($echo, JSON_UNESCAPED_UNICODE);exit;
            }

            if (isset($sign['sign']) && $sign['sign'] != '') {
                $mysign = base64_encode(hash_hmac('sha1', $post, 'ehotel-life', true));
                if ($sign['sign'] == $mysign) {
                    return json_decode($post, true);
                } else {
                    $echo = array(
                        'code' => '10004',
                        'msg' => '签名错误',
                    );

                    echo json_encode($echo, JSON_UNESCAPED_UNICODE);exit;
                }
            } else {
                $echo = array(
                    'code' => '00000',
                    'msg' => '签名不存在',
                );

                echo json_encode($echo, JSON_UNESCAPED_UNICODE);exit;
            }
        }
    }